package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackNumVO;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.jres.util.JresUtil;
import com.cloudbroker.bcs.common.model.SessionIdentity;
import com.cloudbroker.bcs.common.util.*;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.csvc.itn.api.t2service.ITNT2Service;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.*;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.base.UCForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.*;
import com.cloudbroker.bcs.csvc.uf30.api.constants.type.ActionIn;
import com.cloudbroker.bcs.csvc.uf30.api.vo.request.GoldCoinChangeForm;
import com.cloudbroker.bcs.csvc.uf30.api.vo.response.TransIdBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.ChannelCode;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ChatRoomErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.CommonErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.*;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.ListQueryVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.UserFansBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.*;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.*;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.result.GoldChangeResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.result.GoldQryResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.GoldChangeForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.RegisteForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.base.GoldForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.ItnUserInfoBackData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.wechat.vo.PayCallback;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.GetChatroomAddrForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.UserInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.GetChatroomAddrBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.UserManagerT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.YunxinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.common.constant.type.PlatformType;
import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.*;
import com.cloudbroker.bcs.platform.dav.middle.entityview.*;
import com.cloudbroker.bcs.platform.dav.middle.extservice.gold.GoldService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.ltb.LTBService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.point.PointAddService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.uc.UCenterService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.uf30.UF30Service;
import com.cloudbroker.bcs.platform.dav.middle.model.CustomerCache;
import com.cloudbroker.bcs.platform.dav.middle.service.*;
import com.cloudbroker.bcs.platform.dav.middle.util.*;
import com.cloudbroker.bcs.platform.dav.middle.util.point.PointType;
import com.cloudbroker.bsc.common.search.util.SearchTask;
import com.hundsun.jres.common.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
public class UserFansBizServiceImpl implements UserFansBizService {

	private static final Logger logger = LoggerFactory.getLogger(UserFansBizServiceImpl.class);

	@Resource
	private CustomerBrokerRelService customerBrokerRelService;

	@Resource
	private ValidateCodeService validateCodeService;

	@Resource
	private CustomerService customerService;

	@Resource
	private BrokerService brokerService;

	@Resource
	private NoticeSendService noticeSendService;

	@Resource
	private ChatRoomService chatRoomService;

	@Resource
	private ChatTopicService chatTopicService;

	@Resource
	private QuestionService questionService;

	@Resource
	private FeedbackService feedbackService;

	@Resource
	private RechargeWaterService rechargeWaterService;

	@Resource
	private PayWaterService payWaterService;

	@Resource
	private FileService fileService;

	@Resource
	private UF30Service uf30Service;

	@Resource
	private UCenterService uCenterService;

	@Resource
	private LTBService ltbService;

	@Resource
	private NoticeMsgService noticeMsgService;

	@Resource
	private SystemMessageService systemMessageService;

	@Resource
	private YunxinT2BizService yunxinT2;

	@Resource
	private TenantService tenantService;

	@Resource
	private CustomerBrokerFollowService customerBrokerFollowService;

	@Resource
	private AnswerService answerService;

	@Resource
	private ViewpointMsgService viewpointMsgService;

	@Resource
	private PointAddService pointAddService;

	@Resource
	private ViewpointReplyService viewpointReplyService;

	@Resource
	private UpvoteWaterService upvoteWaterService;

	@Resource
	private BrokerManagerService brokerManagerService;

	@Resource
	private WhitelistService whitelistService;

	@Resource
	private PointWaterService pointWaterService;

	@Resource
	private ITNT2Service itnServiceT2;

	@Resource
	private UserManagerT2BizService userManagerT2;

	@Resource
	private ActionService actionService;

	@Resource
	private GoldService goldService;

	@Override
	public UserIdGetBackForm funcUseridGet(UserIdGetForm param) {
		Broker broker = brokerService.getByKey(param.getBroker_key());
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		Long broker_id = broker.getBroker_id();
		LoginType loginType = EnumUtil.valOf(Integer.valueOf(param.getLogin_type()), LoginType.class);
		Customer customer = null;
		UserIdGetBackForm form = null;
		CustomerBrokerRel rel = null;
		switch (loginType) {
		case WEIXIN:
			rel = customerBrokerRelService.getByBrokerIdAndOpenId(broker_id, param.getAccount());
			if (rel == null) {
				form = new UserIdGetBackForm();
				form.setCustomer_key(
						createNewFansInfo(loginType, param.getAccount(), null, broker_id, broker.getTenant_id()));
				return VOUtil.setSuccessResult(form);
			}
			customer = customerService.get(String.valueOf(rel.getCustomer_id()));
			if (customer == null) {
				customerBrokerRelService.deleteByBrokerIdAndCustomerId(rel.getBroker_id(), rel.getCustomer_id());
				form = new UserIdGetBackForm();
				form.setCustomer_key(
						createNewFansInfo(loginType, param.getAccount(), null, broker_id, broker.getTenant_id()));
				return VOUtil.setSuccessResult(form);
			}
			break;
		case CACHE:
			customer = customerService.getByKey(param.getAccount());
			if (customer == null) {
				return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
			}
			break;
		case QQ:
			customer = customerService.getByQQ(param.getAccount());
			break;
		case WEIBO:
			customer = customerService.getByWeibo(param.getAccount());
		default:
			break;
		}
		if (!LoginType.WEIXIN.equals(loginType)) {
			if (customer == null) {
				form = new UserIdGetBackForm();
				form.setCustomer_key(
						createNewFansInfo(loginType, param.getAccount(), null, broker_id, broker.getTenant_id()));
				return VOUtil.setSuccessResult(form);
			}
			rel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker_id, customer.getCustomer_id());
			if (rel == null) {
				customerBrokerRelService.saveNewRel(broker.getTenant_id(), broker_id, customer.getCustomer_id(), null);
			} else if (BlockType.YES.getVal() == rel.getBlock_flag()) {
				return VOUtil.genErrorResult(ClientErr.FANS_IS_BLOCK, UserIdGetBackForm.class);
			}
		}
		// 手机号为空跳到手机号登录页面，昵称为空跳转到完善信息页面
		// 密码为空跳转到完善信息页面
		if (StringUtil.isEmpty(customer.getMobile()) || StringUtil.isEmpty(customer.getCustomer_name())
				|| StringUtil.isEmpty(customer.getPassword())) {
			form = getUserIdFrom(customer);
			return VOUtil.setSuccessResult(form);
		}
		return setLoginReturnForm(broker_id, customer, null);
	}

	@Override
	public UserIdGetBackForm funcUseridGetByTenant(UserIdGetByTenantForm param) {
		Tenant tenant = tenantService.getByKey(param.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, UserIdGetBackForm.class);
		}
		LoginType loginType = EnumUtil.valOf(Integer.valueOf(param.getLogin_type()), LoginType.class);
		Customer customer = null;
		UserIdGetBackForm form = null;
		switch (loginType) {
		case WEIXIN:
			customer = customerService.getByWxOpenId(param.getAccount());
			break;
		case CACHE:
			customer = customerService.getByKey(param.getAccount());
			if (customer == null) {
				return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
			}
			break;
		case QQ:
			customer = customerService.getByQQ(param.getAccount());
			break;
		case WEIBO:
			customer = customerService.getByWeibo(param.getAccount());
			break;
		default:
			break;
		}
		if (customer == null) {
			form = new UserIdGetBackForm();
			form.setCustomer_key(createNewFansInfo(loginType, param.getAccount(), null, null, tenant.getTenant_id()));
			return VOUtil.setSuccessResult(form);
		}
		// 手机号为空跳到手机号登录页面，昵称为空跳转到完善信息页面
		// 密码为空跳转完善信息页面
		if (StringUtil.isEmpty(customer.getMobile()) || StringUtil.isEmpty(customer.getCustomer_name())
				|| StringUtil.isEmpty(customer.getPassword())) {
			form = getUserIdFrom(customer);
			return VOUtil.setSuccessResult(form);
		}
		return setLoginReturnForm(null, customer, null);
	}

	private String createNewFansInfo(LoginType loginType, String account, String mobile, Long broker_id,
			Integer tenant_id) {
		Customer customer = new Customer();
		String customer_key = UUID.randomUUID().toString();
		customer.setCustomer_key(customer_key);
		customer.setCreate_time(new Date());
		customer.setTenant_id(tenant_id);
		String openId = null;
		if (LoginType.WEIXIN.equals(loginType)) {
			openId = account;
			customer.setWx_open_id(openId);
		} else if (LoginType.QQ.equals(loginType)) {
			customer.setQq_open_id(account);
		} else if (LoginType.WEIBO.equals(loginType)) {
			customer.setWeibo_id(account);
		}
		customer.setMobile(mobile);
		customer.setBlock_flag("1");
		customer.setGag_flag("1");
		customer.setFund_flag("1");
		customerService.save(customer);
		if (broker_id != null) {
			customerBrokerRelService.saveNewRel(tenant_id, broker_id, customer.getCustomer_id(), openId);
		}
		return customer_key;
	}

	private UserIdGetBackForm setLoginReturnForm(Long broker_id, Customer customer, String password) {
		UserIdGetBackForm form = new UserIdGetBackForm();
		form.setCustomer_id(customer.getCustomer_id());
		form.setCustomer_key(customer.getCustomer_key());
		form.setCustomer_name(customer.getCustomer_name());
		form.setCustomer_avatar(customer.getAvatar());
		form.setMobile(customer.getMobile());
		form.setWx_open_id(customer.getWx_open_id());
		// 如果云信账号为空，注册云信
		if (StringUtil.isEmpty(customer.getYunxin_accid())) {
			customerService.yunxinReg(customer, true);
		}
		String access_token;
		if (ConfigValues.IsUserCenter() && !ChannelCode.ITN.equals(customer.getReg_source())) {
			UIDBackVo vo;
			if (null == password) {
				// 登录用户中心，返回user_token
				FuncRegisterAndLoginForm param = new FuncRegisterAndLoginForm();
				param.setLogin_account(customer.getMobile());
				param.setAlias_name(customer.getCustomer_name());
				param.setAuth_password(customer.getPassword());
				param.setAvatar(customer.getAvatar());
				param.setMobile(customer.getMobile());
				param.setUser_type("3");
				param.setSex(customer.getSex());
				param.setProvince(customer.getProvince_name());
				param.setCity(customer.getCity_name());
				param.setTenant_id(customer.getTenant_id());
				param.setRegister_flag("1");
				vo = uCenterService.funcRegisterAndLogin(param);
			} else {
				// 密码登录
				FuncLoginForm params = new FuncLoginForm();
				params.setLogin_account(customer.getMobile());
				params.setUser_type("3");
				params.setAuth_password(password);
				params.setTenant_id(customer.getTenant_id());
				vo = uCenterService.funcLogin(params);
			}
			if (VOUtil.isSuccess(vo)) {
				String user_status = vo.getUser_status();
				if (!StringUtil.isBlank(user_status)) {
					if (!"0".equals(user_status)) {
						return VOUtil.genErrorResult(ClientErr.USER_ACCOUNT_STATUS_ERR, UserIdGetBackForm.class);
					}
				}
			} else {
				if ("10055".equals(vo.getError_no())) {
					return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, UserIdGetBackForm.class);
				}
				return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_LOGIN_FAIL, UserIdGetBackForm.class);
			}
			access_token = vo.getUser_token();
			if (null == customer.getUser_id() || !customer.getUser_id().equals(vo.getUser_id())) {
				customer.setUser_id(vo.getUser_id());
				customerService.update(customer);
			}
			// 注册金币系统
			RegisteForm params = new RegisteForm();
			params.setMobile(customer.getMobile());
			params.setUser_token(GoldTokenUtil.getGoldToken());
			params.setUser_id(customer.getCustomer_key());
			params.setTenant_id(String.valueOf(customer.getTenant_id()));
			goldService.goldRegiste(params);
			CustomerCache identity = customerService.createNewFansIdentity(customer, broker_id);
			HSBCPSBizDataContext.setUserCenterId(identity.getUserCenterId());
			SessionHelper.getInstance().renewUCUserInfo(identity, customer.getUser_id());
		} else {
			access_token = saveNewCustomerSession(customer, broker_id);
			HSBCPSBizDataContext.setAccess_token(access_token);
		}

		// 增加积分
		pointAddService.addPoint(customer.getMobile(), PointType.LOGIN, customer.getUser_id(), customer.getTenant_id());
		form.setUser_token(access_token);
		form.setUser_id(customer.getUser_id());
		form.setYunxin_token(customer.getYunxin_token());
		form.setYunxin_acct(customer.getYunxin_accid());
		form.setYunxin_appkey(ConfigValues.getYunxinAppkey());
		form.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
		form.setOss_prefix(ConfigValues.getInterfaceOssAddr());
		if (broker_id != null) {
			this.fansFocusBroker(access_token, customer.getCustomer_id(), broker_id);
			this.setLoginFormWithBroker(broker_id, customer, form);
		}
		String coinsName = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(customer.getTenant_id()))
				.get("tenant.id.coins.name", ConfigValues.COINS_NAME);
		form.setCoin_name(coinsName);
		return VOUtil.setSuccessResult(form);
	}

	private void setLoginFormWithBroker(Long broker_id, Customer customer, UserIdGetBackForm form) {
		CustomerBrokerRel rel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker_id,
				customer.getCustomer_id());
		if (rel != null) {
			form.setBlock_flag(rel.getBlock_flag());
			form.setGag_flag(rel.getGag_flag());
			form.setWx_open_id(rel.getWx_open_id());
		}
		Integer roomId = chatRoomService.setYunxinRoomUrl(form, customer.getYunxin_accid(), broker_id);
		GetChatroomAddrForm params = new GetChatroomAddrForm();
		params.setRoomid(roomId);
		params.setAccid(customer.getYunxin_accid());
		GetChatroomAddrBackVo retMap = yunxinT2.getChatroomAddr(params);
		if (retMap != null) {
			form.setYunxin_broadcast_url(retMap.getAddr());
		}
	}

	@Override
	public UserIdGetBackForm funcMobileLogin(MobileLoginForm param) {
		String mobile = param.getMobile();
		UserIdGetBackForm validForm = mobileLoginValid(mobile, param.getVerify_code(), false);
		if (validForm != null) {
			return validForm;
		}
		Broker broker = brokerService.getByKey(param.getBroker_key());
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		Integer tenant_id = broker.getTenant_id();

		Customer customer = customerService.getByMobile(mobile);
		Customer customerOld = null;
		String openId = null;
		if (!StringUtil.isEmpty(param.getCustomer_key())) {
			customerOld = customerService.getByKey(param.getCustomer_key());
			if (customerOld != null) {
				CustomerBrokerRel tempRel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker.getBroker_id(),
						customerOld.getCustomer_id());
				if (tempRel != null) {
					openId = tempRel.getWx_open_id();
					if (BlockType.YES.getVal() == ValueUtil.getInt(tempRel.getBlock_flag(), 1)) {
						return VOUtil.genErrorResult(ClientErr.FANS_IS_BLOCK, UserIdGetBackForm.class);
					}
				}
			}
		}
		// 手机号不存在
		if (customer == null) {
			customer = this.createNewCustomer(param.getMobile(), tenant_id, customerOld, "");
			customerBrokerRelService.saveNewRel(tenant_id, broker.getBroker_id(), customer.getCustomer_id(), openId);
		} else {
			// 手机号存在
			if (customerOld != null) {
				// brokerKey存在
				copyDataToMobile(customerOld, customer);
				customerService.update(customer);
			}
			CustomerBrokerRel relTemp = customerBrokerRelService.getByBrokerIdAndCustomerId(broker.getBroker_id(),
					customer.getCustomer_id());
			if (relTemp == null) {
				customerBrokerRelService.saveNewRel(tenant_id, broker.getBroker_id(), customer.getCustomer_id(),
						openId);
			} else {
				if (BlockType.YES.getVal() == ValueUtil.getInt(relTemp.getBlock_flag(), 1)) {
					return VOUtil.genErrorResult(ClientErr.FANS_IS_BLOCK, UserIdGetBackForm.class);
				}
				// 如果原数据的openId不为空，说明用户是从微信登录的，把原来的OpenID放过来
				if (!StringUtil.isEmpty(openId)) {
					relTemp.setWx_open_id(openId);
					customerBrokerRelService.update(relTemp);
				}
			}
		}
		UserIdGetBackForm form = null;
		// 昵称为空跳转到完善信息页面
		// 密码为空跳转到完善信息页面
		if (StringUtil.isEmpty(customer.getCustomer_name()) || StringUtil.isEmpty(customer.getPassword())) {
			form = getUserIdFrom(customer);
			return VOUtil.setSuccessResult(form);
		}
		return setLoginReturnForm(broker.getBroker_id(), customer, null);
	}

	private UserIdGetBackForm mobileLoginValid(String mobile, String verify_code, boolean tenantLoginFlag) {
		// if (!StringUtil.isEmpty(customer_key)) {
		// // customerkey不为空说明是第三方登录跳转过来的，姓名必传
		// if (StringUtil.isEmpty(customer_name)) {
		// return VOUtil.genErrorResult(BasicErrorCodes.PARAM_ERROR,
		// UserIdGetBackForm.class);
		// }
		// }
		Integer verifySource = tenantLoginFlag ? VerifySource.FANS_LOGIN_BY_TENANT.getVal()
				: VerifySource.FANS_LOGIN.getVal();
		if (!validateCodeService.checkCodeTime(mobile, "", verifySource)) {
			return VOUtil.genErrorResult(CommonErr.VALIDAET_CODE_TIMT_OUT, UserIdGetBackForm.class);
		}
		if (!validateCodeService.checkCode(verify_code, mobile, "", verifySource)) {
			return VOUtil.genErrorResult(CommonErr.VERIFY_CODE_WRONG, UserIdGetBackForm.class);
		}
		return null;
	}

	@Override
	public UserIdGetBackForm funcMobileLoginByTenant(MobileLoginByTenantForm param) {
		String mobile = param.getMobile();
		UserIdGetBackForm validForm = mobileLoginValid(mobile, param.getVerify_code(), true);
		if (validForm != null) {
			return validForm;
		}
		Tenant tenant = tenantService.getByKey(param.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, UserIdGetBackForm.class);
		}
		Customer customer = customerService.getByMobile(mobile);
		Customer customerOld = null;
		if (!StringUtil.isEmpty(param.getCustomer_key())) {
			customerOld = customerService.getByKey(param.getCustomer_key());
			if (customerOld != null) {
				if (!StringUtil.isEmpty(customerOld.getMobile())) {
					// customemrkey不为空说明第三方登录完成,没有手机号才会进入此方法，如果手机号存在，返回错误。
					return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, UserIdGetBackForm.class);
				}
			}
		}
		Integer tenant_id = tenant.getTenant_id();
		// 手机号不存在
		if (customer == null) {
			// customerkey不存在
			customer = this.createNewCustomer(param.getMobile(), tenant_id, customerOld, "");
		} else {
			// 手机号存在
			if (customerOld != null) {
				// brokerKey存在
				copyDataToMobile(customerOld, customer);
				customerService.update(customer);
			}
		}
		UserIdGetBackForm form = null;
		// 昵称为空跳转到完善信息页面
		// 密码为空跳转到完善信息页面
		if (StringUtil.isEmpty(customer.getCustomer_name()) || StringUtil.isEmpty(customer.getPassword())) {
			form = getUserIdFrom(customer);
			return VOUtil.setSuccessResult(form);
		}
		return setLoginReturnForm(null, customer, null);
	}

	@Override
	public CustomerAccountTypeBack funcIsCapitalAccount(HSBCPSVO form) {
		UCForm param = new UCForm();
		String access_token = AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal());
		param.setUser_token(form.getUser_token());
		CustomerAccountType customerAccountType = uCenterService.funcIsCapitalAccount(param);
		CustomerAccountTypeBack result = new CustomerAccountTypeBack();
		result.setIs_capital_account(ValueUtil.getInt(customerAccountType.getIs_capital_account()));
		result.setAccess_token(access_token);
		return VOUtil.setSuccessResult(result);
	}

	private UserIdGetBackForm getUserIdFrom(Customer customer) {
		UserIdGetBackForm form;
		form = new UserIdGetBackForm();
		form.setCustomer_key(customer.getCustomer_key());
		form.setMobile(customer.getMobile());
		form.setCustomer_name(customer.getCustomer_name());
		return form;
	}

	@Override
	public UserIdGetBackForm funcPasswordLogin(PasswordLoginForm param) {
		String mobile = param.getMobile();
		String password = param.getPassword();
		String broker_key = param.getBroker_key();
		Broker broker = brokerService.getByKey(broker_key);
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		Customer customer = customerService.getByMobileAndTenant(mobile, broker.getTenant_id());
		if (null == customer) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		return setLoginReturnForm(broker.getBroker_id(), customer, MD5Util.encrypt(password));
	}

	@Override
	public UserIdGetBackForm funcPasswordLoginByTenant(PasswordLoginByTenantForm param) {
		String mobile = param.getMobile();
		String password = param.getPassword();
		String tenant_key = param.getTenant_key();
		Tenant tenant = tenantService.getByKey(tenant_key);
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, UserIdGetBackForm.class);
		}
		Customer customer = customerService.getByMobileAndTenant(mobile, tenant.getTenant_id());
		if (null == customer) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		return setLoginReturnForm(null, customer, MD5Util.encrypt(password));
	}

	@Override
	public HSBCPSBackVO funcFansResetPassword(ResetPasswordForm param) {
		String mobile_tel = param.getMobile();
		String new_password = param.getNew_password();
		String verify_code = param.getVerify_code();

		Customer customer = customerService.getByMobile(mobile_tel);
		if (null == customer) {
			return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
		}

		FuncPasswordResetForm form = new FuncPasswordResetForm();
		form.setLogin_account(mobile_tel);
		form.setAuth_code(verify_code);
		form.setAuth_password(MD5Util.encrypt(new_password));
		form.setUser_type("3");
		form.setTenant_id(customer.getTenant_id());
		HSBCPSBackVO vo = uCenterService.funcPasswordReset(form);
		if (!VOUtil.isSuccess(vo)) {
			return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR, HSBCPSBackVO.class);
		}

		/*
		 * if (!validateCodeService.checkCodeTime(mobile_tel, "",
		 * VerifySource.RESET_PASSWORD.getVal())) { SessionHelper sessionHelper
		 * = SessionHelper.getInstance(); CacheHelper cacheHelper =
		 * CacheHelper.getInstance(); String mobileVerifyKey =
		 * sessionHelper.getSendVerifyKeyConfig(mobile_tel,
		 * ValueUtil.getString(VerifySource.RESET_PASSWORD.getVal())); long
		 * today = System.currentTimeMillis(); String time =
		 * cacheHelper.get(mobileVerifyKey); Map<String, Object> cifMap = new
		 * HashMap<>(); int outTime = ConfigValues.getMobileVerifyCodeTimeout();
		 * long time_out = 120000; if (!StringUtil.isEmpty(time)) { time_out =
		 * today - Long.parseLong(time); } cifMap.put("time_out", outTime -
		 * time_out / 1000); return
		 * VOUtil.genErrorResultVo(CommonErr.VALIDAET_CODE_TIMT_OUT); } if
		 * (!validateCodeService.checkCode(verify_code, mobile_tel, "",
		 * VerifySource.RESET_PASSWORD.getVal())) { return
		 * VOUtil.genErrorResultVo(CommonErr.VERIFY_CODE_WRONG); }
		 */

		customer.setPassword(MD5Util.encrypt(new_password));
		customerService.update(customer);
		return VOUtil.genSuccessBackVo();
	}

	@Override
	public UserIdGetBackForm funcUserInfoComplet(UserInfoCompletForm form) {
		Broker broker = brokerService.getByKey(form.getBroker_key());
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}
		return completeUserInfo(form, broker.getBroker_id());
	}

	@Override
	public HSBCPSBackVO funcCheckInvitationCode(InvitationCodeForm form) {
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		if (brokerId == null) {
			brokerId = ValueUtil.getLong(form.getBroker_id());
		}
		Long customerId = HSBCPSBizDataContext.getCustomer().getCustomer_id();
		CacheHelper cacheHelper = CacheHelper.getInstance();
		String rightKey = CacheKeys.BROKER_RIGHT_INVITATION_CODE;
		String invitationCode1 = cacheHelper.hget(rightKey, String.valueOf(brokerId));
		String customerKey = CacheKeys.CUSTOMER_INVITATION_CODE;
		String field = customerId + "." + brokerId;
		String invitationCode2 = cacheHelper.hget(customerKey, field);

		if (invitationCode1 == null) {
			return VOUtil.genSuccessBackVo();
		}
		if (invitationCode1 == "nil") {
			return VOUtil.genSuccessBackVo();
		}
		// 黑名单判断
		CustomerBrokerRel rel = customerBrokerRelService.getByBrokerIdAndCustomerId(brokerId, customerId);
		if (rel != null) {
			if (rel.getBlock_flag() != null && rel.getBlock_flag() == 0) {
				return VOUtil.genErrorResultVo(ClientErr.FANS_IS_BLOCK);
			}
		}
		// 白名单用户判断
		Whitelist white = whitelistService.queryByBrokerIdAndMobile(brokerId,
				HSBCPSBizDataContext.getCustomer().getMobile());
		if (white != null) {
			return VOUtil.genSuccessBackVo();
		}
		if (invitationCode2 != null && invitationCode2 != "nil") {
			if (invitationCode1.equals(invitationCode2)) {
				return VOUtil.genSuccessBackVo();
			}
		}
		if (form.getInvitation_code() != null) {
			if (invitationCode1.equals(form.getInvitation_code())) {
				cacheHelper.hset(customerKey, field, form.getInvitation_code());
				return VOUtil.genSuccessBackVo();
			}
		}
		return VOUtil.genErrorResult(ClientErr.INVITATION_CODE_ERR, HSBCPSBackVO.class);

	}

	private UserIdGetBackForm completeUserInfo(UserInfoCompletBaseForm form, Long broker_id) {
		if (checkUserName(form.getCustomer_name())) {
			return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, UserIdGetBackForm.class);
		}
		Customer customer = customerService.getByKey(form.getCustomer_key());
		if (customer == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserIdGetBackForm.class);
		}

		customer.setAvatar(form.getCustomer_avatar());
		customer.setPassword(MD5Util.encrypt(form.getPassword()));
		customer.setCustomer_name(form.getCustomer_name());
		setOssAvatarToCustomer(form.getCustomer_avatar(), customer, false);
		customerService.update(customer);
		// 手机号为空跳到手机号登录页面
		if (StringUtil.isEmpty(customer.getMobile())) {
			UserIdGetBackForm result = new UserIdGetBackForm();
			result.setCustomer_key(customer.getCustomer_key());
			result.setMobile(customer.getMobile());
			result.setCustomer_name(customer.getCustomer_name());
			return VOUtil.setSuccessResult(result);
		}
		UserIdGetBackForm ret = setLoginReturnForm(broker_id, customer, null);
		return ret;
	}

	@Override
	public UserIdGetBackForm funcUserInfoCompletByTenant(UserInfoCompletByTenantForm form) {
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, UserIdGetBackForm.class);
		}
		return this.completeUserInfo(form, null);
	}

	@Override
	public HSBCPSBackVO funcFansFollowBroker(FollowBrokerForm form) {
		HSBCPSBizDataContext.getCustomer();
		Long brokerId = Long.parseLong(form.getBroker_id());
		Long customerId = HSBCPSBizDataContext.getClientId();
		CustomerBrokerFollow customerBrokerFollow = customerBrokerFollowService.getByBrokerIdAndCustomerId(brokerId,
				customerId);
		if (customerBrokerFollow != null) {
			return VOUtil.genErrorResult(ClientErr.HAS_FOLLOW_BROKER, HSBCPSBackVO.class);
		}
		customerBrokerFollow = new CustomerBrokerFollow();
		customerBrokerFollow.setCustomer_id(customerId);
		customerBrokerFollow.setBroker_id(brokerId);
		customerBrokerFollow.setCreate_time(new Date());
		customerBrokerFollowService.save(customerBrokerFollow);
		HSBCPSBackVO result = new HSBCPSBackVO();
		return VOUtil.setSuccessResult(result);
	}

	@Override
	public HSBCPSBackVO funcFansCancelFollowBroker(FollowBrokerForm form) {
		HSBCPSBizDataContext.getCustomer();
		Long brokerId = Long.parseLong(form.getBroker_id());
		Long customerId = HSBCPSBizDataContext.getClientId();
		customerBrokerFollowService.deleteByBrokerIdAndCustomerId(brokerId, customerId);
		HSBCPSBackVO result = new HSBCPSBackVO();
		return VOUtil.setSuccessResult(result);
	}

	@Override
	public FollowBrokerResult funcFansClickBroker(FollowBrokerForm form) {
		Long brokerId = Long.parseLong(form.getBroker_id());
		Long customerId = HSBCPSBizDataContext.getClientId();
		Customer customer = HSBCPSBizDataContext.getCustomer();

		Broker broker = brokerService.get(String.valueOf(brokerId));
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, FollowBrokerResult.class);
		}
		CustomerBrokerRel relTemp = customerBrokerRelService.getByBrokerIdAndCustomerId(brokerId, customerId);
		if (relTemp == null) {
			customerBrokerRelService.saveNewRel(HSBCPSBizDataContext.getTenantId(), brokerId, customerId, null);
		} else if (BlockType.YES.getVal() == ValueUtil.getInt(relTemp.getBlock_flag(), 1)) {
			return VOUtil.genErrorResult(ClientErr.FANS_IS_BLOCK, FollowBrokerResult.class);
		}
		this.fansFocusBroker(HSBCPSBizDataContext.getAccess_token(), customerId, brokerId);

		UserIdGetBackForm tempResult = new UserIdGetBackForm();
		this.setLoginFormWithBroker(brokerId, customer, tempResult);
		FollowBrokerResult result = new FollowBrokerResult();
		result.setAll_gag_flag(tempResult.getAll_gag_flag());
		result.setBlock_flag(tempResult.getBlock_flag());
		result.setGag_flag(tempResult.getGag_flag());
		result.setRoom_status(tempResult.getRoom_status());
		result.setYunxin_broadcast_url(tempResult.getYunxin_broadcast_url());
		result.setYunxin_room_id(tempResult.getYunxin_room_id());
		return VOUtil.setSuccessResult(result);
	}

	@Override
	public OnlineNumResultByFans funcChatRoomOnlineNumByFans(HSBCPSVO form) {
		Integer online_num = -1;
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
		if (chatRoom == null) {
			return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, OnlineNumResultByFans.class);
		}
		Integer show_flag = ValueUtil.getIntObj(chatRoom.getShow_person_num_flag(), ConfigValues.ONLINE_NUM_SHOW_FLAG);
		Integer show_threshold = ValueUtil.getIntObj(chatRoom.getShow_person_num_threshold(),
				ConfigValues.ONLINE_NUM_SHOW_THRESHOLD);
		OnlineNumResultByFans onlineNumResultByFans = new OnlineNumResultByFans();
		/* 不显示，返回-1 */
		if (show_flag.equals(1)) {
			Set<String> newFansList = SessionHelper.getInstance().getNewOnlineList(String.valueOf(brokerId));
			Set<String> oldFansList = SessionHelper.getInstance().getOldOnlineList(String.valueOf(brokerId));
			newFansList.addAll(oldFansList);
			/* 小于阈值，返回-1 */
			online_num = newFansList.size() <= show_threshold ? -1 : newFansList.size();
		}
		onlineNumResultByFans.setOnline_num(online_num);
		return VOUtil.setSuccessResult(onlineNumResultByFans);

	}

	private Customer createNewCustomer(String mobile_tel, Integer tenant_id, Customer customerOld, String reg_source) {
		Customer c = new Customer();
		// String password = MD5Util.encrypt("1234567").toLowerCase();
		// 查询用户中心粉丝信息，如果有则设置密码，没有创建一个没有密码的用户
		if (ConfigValues.IsUserCenter()) {
			FuncLoginForm param = new FuncLoginForm();
			param.setLogin_account(mobile_tel);
			param.setTenant_id(tenant_id);
			param.setUser_type("3");
			UserInfoBackVo vo = uCenterService.funcUserBasicInfo(param);
			if (VOUtil.isSuccess(vo)) {
				c.setPassword("usercenterpwd");
				c.setAvatar(vo.getAvatar());
				c.setCustomer_name(vo.getAlias_name());
			}
		}

		c.setCustomer_key(UUID.randomUUID().toString());
		c.setTenant_id(tenant_id);
		c.setCreate_time(new Date());
		c.setMobile(mobile_tel);
		c.setStatus(CustomerStatus.NOMAL.getVal());
		if (customerOld != null) {
			copyDataToMobile(customerOld, c);
		}
		c.setFund_flag("1");
		c.setGag_flag("1");
		c.setBlock_flag("1");
		c.setReg_source(reg_source);
		customerService.save(c);
		customerService.yunxinReg(c, true);
		// setOssAvatarToCustomer(userAvatar, c, true);
		pointAddService.addPoint(mobile_tel, PointType.MOBILE_REG, c.getUser_id(), c.getTenant_id());
		return c;
	}

	// 检测该租户下面是否已经有昵称，有返回true,没有返回false
	private boolean checkUserName(String name) {
		Integer total = brokerManagerService.checkUserName(name) + customerService.checkUserName(name);
		if (total > 0) {
			return true;
		}
		return false;
	}

	private void setOssAvatarToCustomer(String userAvatar, Customer c, boolean updateDatabase) {
		c.setAvatar(userAvatar);
		userAvatar = fileService.transLocalFileUri(userAvatar, false, c.getCustomer_id());
		if (!StringUtil.isEmpty(userAvatar)) {
			c.setAvatar(userAvatar);
			if (updateDatabase) {
				customerService.update(c);
			}
		}
	}

	private void copyDataToMobile(Customer customerOld, Customer c) {
		if (c.getAvatar() == null) {
			c.setAvatar(customerOld.getAvatar());
		}
		if (c.getCustomer_name() == null) {
			c.setCustomer_name(customerOld.getCustomer_name());
		}
		if (customerOld.getQq_open_id() != null) {
			c.setQq_open_id(customerOld.getQq_open_id());
		}
		if (customerOld.getWeibo_id() != null) {
			c.setWeibo_id(customerOld.getWeibo_id());
		}
		if (customerOld.getWx_open_id() != null) {
			c.setWx_open_id(customerOld.getWx_open_id());
		}
		customerService.delete(String.valueOf(customerOld.getCustomer_id()));
		customerBrokerRelService.deleteByCustomerId(customerOld.getCustomer_id());
	}

	@Override
	public HSBCPSBackVO funcCustomerLogout(HSBCPSVO param) {
		String access_token = param.getUser_token();

		// 退出用户中心
		if (ConfigValues.IsUserCenter()) {
			UCForm form = new UCForm();
			form.setUser_token(access_token);
			uCenterService.funcLogout(form);
		}

		Long broker_id = HSBCPSBizDataContext.getBrokerId();
		Long customer_id = HSBCPSBizDataContext.getCustomer().getCustomer_id();
		String access_tokenKey = SessionHelper.getInstance().getClient_idKey(PlatformType.MOBILE,
				String.valueOf(customer_id));
		SessionHelper.getInstance().delete(access_tokenKey);
		SessionHelper.getInstance().destroySession(access_token);
		SessionHelper.getInstance().removeOnlineFromList(String.valueOf(broker_id), String.valueOf(customer_id));
		HSBCPSBizDataContext.removeCustomer();
		return VOUtil.genSuccessBackVo();
	}

	@Override
	public UserInfoBackForm funcUserInfoQry(HSBCPSVO param) {
		UserInfoBackForm backData = new UserInfoBackForm();
		Customer customer = HSBCPSBizDataContext.getCustomer();
		Long broker_id = HSBCPSBizDataContext.getBrokerId();
		backData.setUser_token(param.getUser_token());
		backData.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));

		UserIdGetBackForm form = new UserIdGetBackForm();
		form.setCustomer_id(customer.getCustomer_id());
		form.setCustomer_key(customer.getCustomer_key());
		form.setCustomer_name(customer.getCustomer_name());
		form.setCustomer_avatar(customer.getAvatar());
		form.setMobile(customer.getMobile());
		form.setWx_open_id(customer.getWx_open_id());
		// 如果云信账号为空，注册云信
		if (StringUtil.isEmpty(customer.getYunxin_accid())) {
			customerService.yunxinReg(customer, true);
		}

		form.setYunxin_token(customer.getYunxin_token());
		form.setYunxin_acct(customer.getYunxin_accid());
		form.setYunxin_appkey(ConfigValues.getYunxinAppkey());
		form.setOss_prefix(ConfigValues.getInterfaceOssAddr());
		if (broker_id != null) {
			this.fansFocusBroker(backData.getAccess_token(), customer.getCustomer_id(), broker_id);
			this.setLoginFormWithBroker(broker_id, customer, form);
		}
		String coinsName = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(customer.getTenant_id()))
				.get("tenant.id.coins.name", ConfigValues.COINS_NAME);
		form.setCoin_name(coinsName);

		backData.setAll_gag_flag(form.getAll_gag_flag());
		backData.setBlock_flag(form.getBlock_flag());
		backData.setGag_flag(form.getGag_flag());
		backData.setCoin_name(form.getCoin_name());

		backData.setCustomer_avatar(customer.getAvatar());
		backData.setCustomer_id(form.getCustomer_id());
		backData.setCustomer_key(customer.getCustomer_key());
		backData.setCustomer_name(form.getCustomer_name());

		backData.setYunxin_broadcast_url(form.getYunxin_broadcast_url());
		backData.setYunxin_room_id(form.getYunxin_room_id());
		backData.setYunxin_token(form.getYunxin_token());
		backData.setYunxin_acct(form.getYunxin_acct());
		backData.setYunxin_appkey(form.getYunxin_appkey());

		backData.setMobile(form.getMobile());
		backData.setOss_prefix(form.getOss_prefix());
		backData.setRoom_status(form.getRoom_status());

		backData.setCustomer_profile(customer.getProfile());
		backData.setQq(customer.getQq_open_id());
		backData.setEmail(customer.getEmail());

		backData.setTenant_id(customer.getTenant_id());
		backData.setUser_id(customer.getUser_id());
		return VOUtil.setSuccessResult(backData);
	}

	@Override
	public HSBCPSBackNumVO funcNoreadNoticeQry(HSBCPSVO param) {
		Customer customer = HSBCPSBizDataContext.getCustomer();
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		String key = CacheKeys.NOTICE_SEND + brokerId;
		CacheHelper cacheHelper = CacheHelper.getInstance();
		Integer num = ValueUtil.getInt(cacheHelper.hget(key, String.valueOf(customer.getCustomer_id())), 0);
		HSBCPSBackNumVO form = new HSBCPSBackNumVO();
		form.setNum(num);
		return VOUtil.setSuccessResult(form);
	}

	@Override
	public HSBCPSBackNumVO funcQuestionNumQry(HSBCPSVO param) {
		Customer customer = HSBCPSBizDataContext.getCustomer();
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		Question example = new Question();
		example.setCustomer_id(customer.getCustomer_id());
		example.setBroker_id(brokerId);
		Integer num = questionService.count(example);
		HSBCPSBackNumVO form = new HSBCPSBackNumVO();
		form.setNum(num);
		return VOUtil.setSuccessResult(form);
	}

	@Override
	public HSBCPSBackVO funcUpdateUserAvatar(UpdateUserAvatarForm param) {
		String customer_avatar = param.getCustomer_avatar();
		// 更新用户中心信息
		FuncUserUpdateForm form = new FuncUserUpdateForm();
		form.setAvatar(customer_avatar);
		form.setUser_token(HSBCPSBizDataContext.getAccess_token());
		HSBCPSBackVO vo = uCenterService.funcUserUpdate(form);
		if (!VOUtil.isSuccess(vo)) {
			logger.error("用户中心更新信息失败：" + vo.getError_info());
			return VOUtil.genErrorResultVo(ClientErr.USER_INFO_UPDATE_ERROR);
		}
		Customer customer = HSBCPSBizDataContext.getCustomer();
		// 云信更新用户名片
		UserInfoForm res = new UserInfoForm();
		res.setAccid(customer.getYunxin_accid());
		res.setIcon(customer_avatar);
		yunxinT2.updateUserInfo(res);

		customer.setAvatar(customer_avatar);
		customer.setUpdate_time(new Date());
		customer.setUpdate_by(customer.getCustomer_id());
		customerService.update(customer);

		Map<String, String> mapUpdate = new HashMap<String, String>();
		mapUpdate.put("customer_avatar", customer_avatar);
		Map<String, String> mapQry = new HashMap<String, String>();
		mapQry.put("customer_id", "es equals " + customer.getCustomer_id());
		SearchTask.updateBitchTask(mapQry, mapUpdate);

		// 修改缓存中的用户信息
		CustomerCache cache = SessionHelper.getInstance().fetchSessionIdentity(CustomerCache.class);
		if (null != cache) {
			cache.setCustomer(customer);
			SessionHelper.getInstance().renewIdentity(cache);
		}
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public HSBCPSBackVO funcUpdateUserName(UpdateUserNameForm param) {
		String customer_name = param.getCustomer_name();
		if (checkUserName(customer_name)) {
			return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
		}

		// 更新用户中心信息
		FuncUserUpdateForm form = new FuncUserUpdateForm();
		form.setUser_token(HSBCPSBizDataContext.getAccess_token());
		form.setAlias_name(customer_name);
		HSBCPSBackVO vo = uCenterService.funcUserUpdate(form);
		if (!VOUtil.isSuccess(vo)) {
			if ("10055".equals(vo.getError_no())) {
				return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
			}
			return VOUtil.genErrorResultVo(ClientErr.USER_INFO_UPDATE_ERROR);
		}

		Customer customer = HSBCPSBizDataContext.getCustomer();
		// 云信更新用户名片
		UserInfoForm res = new UserInfoForm();
		res.setAccid(customer.getYunxin_accid());
		res.setName(customer_name);
		yunxinT2.updateUserInfo(res);

		customer.setCustomer_name(customer_name);
		customer.setUpdate_time(new Date());
		customer.setUpdate_by(customer.getCustomer_id());
		customerService.update(customer);

		Map<String, String> mapUpdate = new HashMap<String, String>();
		mapUpdate.put("customer_name", customer_name);
		Map<String, String> mapQry = new HashMap<String, String>();
		mapQry.put("customer_id", "es equals " + customer.getCustomer_id());
		SearchTask.updateBitchTask(mapQry, mapUpdate);
		// 修改缓存中的用户信息
		CustomerCache cache = SessionHelper.getInstance().fetchSessionIdentity(CustomerCache.class);
		if (null != cache) {
			cache.setCustomer(customer);
			SessionHelper.getInstance().renewIdentity(cache);
		}
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public HSBCPSBackVO funcSuggestionAdd(SuggestionAddForm param) {
		Feedback fd = new Feedback();
		fd.setCreate_time(new Date());
		fd.setFeedback_content(param.getSuggestion());
		fd.setSend_id(HSBCPSBizDataContext.getCustomer().getCustomer_id());
		feedbackService.save(fd);
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public HSBCPSBackVO funcUserRecharge(PayCallback param) {
		logger.debug("---------->   充值回调          <---------");
		GoldChangeResult backVo = new GoldChangeResult();
		String result_code = param.getTrxstatus();
		String trxid = param.getTrxid();
		String occur_amount = param.getTrxamt();

		RechargeWater rw = rechargeWaterService.getByTrxid(trxid);
		Long customer_id = rw.getCustomer_id();
		Integer tenant_id = rw.getTenant_id();
		String order_id = rw.getTrans_id();

		Customer c = customerService.getById(customer_id, tenant_id);

		if ("0000".equals(result_code)) {
			// 调用金币系统充值
			GoldChangeForm form = new GoldChangeForm();
			form.setUser_token(GoldTokenUtil.getGoldToken());
			form.setTenant_id(String.valueOf(tenant_id));
			form.setUser_id(c.getCustomer_key());
			form.setExtrans_id(order_id);
			form.setOccur_amount(ValueUtil.getString(ValueUtil.getDecimal(occur_amount, BigDecimal.ZERO)
					.divide(BigDecimal.TEN, 0, BigDecimal.ROUND_HALF_UP)));
			form.setAction_type(ReChargeType.CHARGE.getVal());
			backVo = goldService.goldChange(form);
			if (VOUtil.isSuccess(backVo)) {
				rw.setCharge_status(RechargeStatus.SUC.getVal());
				rw.setCharge_status_mean("充值成功");
			} else {
				rw.setCharge_status(RechargeStatus.ERR.getVal());
				rw.setCharge_status_mean("调金币系统失败:" + backVo.getError_info());
			}
		} else {
			rw.setCharge_status(RechargeStatus.ERR.getVal());
			rw.setCharge_status_mean("通联充值失败");
		}

		String uf30transId = backVo.getTrans_id();
		rw.setUf30_trans_no(uf30transId);
		rw.setPosition_str(PositionStrUtil.getPositionStr());
		rechargeWaterService.update(rw);
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public ConsumeDetailBackList funcConsumeDetailQry(ConsumeDetailQryForm param) {
		Date startTime = null;
		Date endTime = null;
		try {
			if (!StringUtil.isBlank(param.getStart_time())) {
				startTime = DateTimeUtil
						.getStartOfDay(DateTimeUtil.toDate(param.getStart_time(), DateTimeUtil.FORMAT_YYYYMMDD));
			}
			if (!StringUtil.isBlank(param.getEnd_time())) {
				endTime = DateTimeUtil
						.getEndOfDay(DateTimeUtil.toDate(param.getEnd_time(), DateTimeUtil.FORMAT_YYYYMMDD));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("customerId", HSBCPSBizDataContext.getCustomer().getCustomer_id());
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("position_str", param.getPosition_str());
		map.put("request_num", Integer.valueOf(param.getRequest_num()));
		List<ConsumeDetailBackView> list = payWaterService.queryDetailList(map);
		List<ConsumeDetailBackForm> reList = new ArrayList<>();
		reList.addAll(list);
		ConsumeDetailBackList backList = new ConsumeDetailBackList();
		backList.setData_list(reList);
		return VOUtil.setSuccessResult(backList);
	}

	@Override
	public HSBCPSBackNumVO funcUserAmountQry(HSBCPSVO param) {
		Customer customer = HSBCPSBizDataContext.getCustomer();
		GoldForm gform = new GoldForm();
		gform.setUser_id(customer.getCustomer_key());
		gform.setUser_token(GoldTokenUtil.getGoldToken());
		GoldQryResult backVo = goldService.userCurGoldQry(gform);
		if (!VOUtil.isSuccess(backVo)) {
			return VOUtil.genErrorResult(ClientErr.AMOUNT_QRY_FAIL, HSBCPSBackNumVO.class);
		}
		HSBCPSBackNumVO form = new HSBCPSBackNumVO();
		BigDecimal amount = ValueUtil.getBigDecimal(backVo.getCurrent_amount());
		form.setNum(ValueUtil.getInt(amount.intValue()));
		return VOUtil.setSuccessResult(form);
	}

	@Override
	public NoticeQryBackList funcNoticeListQry(NoticeForm param) {
		Long broker_id = HSBCPSBizDataContext.getBrokerId();
		String position_str = param.getPosition_str();
		Integer request_num = Integer.parseInt(param.getRequest_num());
		if (request_num < SysContants.MIN_REQUEST_NUM || request_num > SysContants.MAX_REQUEST_NUM) {
			request_num = ConfigValues.getRequestNum();
		}

		// 如果是滚动通知，直接从noticemsg表里查
		Integer notice_type = Integer.valueOf(param.getNotice_type());

		NoticeQryBackList list = new NoticeQryBackList();
		if (NoticeType.ROLL.equals(EnumUtil.valOf(notice_type, NoticeType.class))) {
			Long brokerId = HSBCPSBizDataContext.getBrokerId();
			List<NoticeMsgView> rollList = noticeMsgService.getRollNotices(brokerId, position_str, request_num,
					notice_type);
			list.setData_list(getList(rollList));
			return VOUtil.setSuccessResult(list);
		}

		Map<String, Object> params = new HashMap<String, Object>();
		params.put(HSBCPSFields.BROKER_ID, broker_id);
		params.put(HSBCPSFields.POSITION_STR, position_str);
		params.put(HSBCPSFields.REQUEST_NUM, request_num);
		List<SystemMsgView> msgs = systemMessageService.getCustomerNotice(params);
		list.setData_list(getSysList(msgs));
		Customer customer = HSBCPSBizDataContext.getCustomerNoException();
		if (customer != null) {
			Long customer_id = customer.getCustomer_id();
			String key = CacheKeys.NOTICE_SEND + broker_id;
			CacheHelper cacheHelper = CacheHelper.getInstance();
			cacheHelper.hset(key, String.valueOf(customer_id), String.valueOf(0));
		}
		return VOUtil.setSuccessResult(list);
	}

	private List<NoticeQryBackForm> getSysList(List<SystemMsgView> systemList) {
		List<NoticeQryBackForm> backList = new ArrayList<NoticeQryBackForm>();

		for (SystemMsgView n : systemList) {
			NoticeQryBackForm form = new NoticeQryBackForm();
			form.setBroker_id(n.getBroker_id());
			form.setNotice_content(n.getNotice_content());
			form.setNotice_title(n.getNotice_title());
			form.setSend_time(n.getSend_time());
			form.setPosition_str(n.getPosition_str());
			backList.add(form);
		}
		return backList;
	}

	private List<NoticeQryBackForm> getList(List<NoticeMsgView> rollList) {
		List<NoticeQryBackForm> backList = new ArrayList<NoticeQryBackForm>();

		for (NoticeMsgView n : rollList) {
			NoticeQryBackForm form = new NoticeQryBackForm();
			form.setBroker_id(n.getBroker_id());
			form.setNotice_id(n.getNotice_id());
			form.setRead_flag(n.getRead_flag());
			form.setNotice_content(n.getNotice_content());
			form.setNotice_title(n.getNotice_title());
			form.setSend_time(n.getSend_time());
			form.setRead_time(n.getRead_time());
			form.setPosition_str(n.getPosition_str());
			backList.add(form);
		}
		return backList;
	}

	private String saveNewCustomerSession(Customer customer, Long brokerId) {
		Long client_id = customer.getCustomer_id();
		PlatformType type = PlatformType.MOBILE;
		// 根据clientId 获取 客户的 access_token,获取到token 把当前的token 注销掉
		String clientIdToken = SessionHelper.getInstance().getSessionTokenByClientId(type, client_id.toString());
		// 客户已经存在token，删除token
		if (!StringUtil.isBlank(clientIdToken)) {
			// 销毁会话令牌
			SessionHelper.getInstance().delete(clientIdToken);
		}
		CustomerCache identity = customerService.createNewFansIdentity(customer, brokerId);
		// 缓存
		String access_token = SessionHelper.getInstance().renewAccess_token(identity);

		// 把生成的token保存到缓存
		SessionHelper.getInstance().saveNewClientIDSession(type, client_id, access_token, customer.getTenant_id(),
				null);
		return access_token;
	}

	private void fansFocusBroker(String access_token, Long customerId, Long brokerId) {
		// 如果接入用户中心则不需要标识已关注该投顾
		CustomerCache cache = SessionHelper.getInstance().fetchSessionIdentity(CustomerCache.class);
		cache.setBrokerId(brokerId);
		SessionHelper.getInstance().renewIdentity(cache);

		customerBrokerRelService.updateOnlineStatus(brokerId, customerId, OnlineStatus.ONLINE.getVal());
		// 加入到在线用户列表缓存
		SessionHelper.getInstance().addOneToBrokeyOnline(String.valueOf(brokerId), String.valueOf(customerId));
	}

	private void fansBackList(String access_token, Long customerId, Long brokerId) {
		CustomerCache cache = SessionHelper.getInstance().fetchSessionIdentity(CustomerCache.class);
		cache.setBrokerId(null);
		SessionHelper.getInstance().renewIdentity(cache);
		customerBrokerRelService.updateOnlineStatus(brokerId, customerId, OnlineStatus.NOT_ONLINE.getVal());
		// 在线用户列表缓存移除数据
		SessionHelper.getInstance().removeOnlineFromList(String.valueOf(brokerId), String.valueOf(customerId));
	}

	@Override
	public HSBCPSBackVO funcFansRecharge(HSBCPSVO form) {
		Customer c = HSBCPSBizDataContext.getCustomer();
		Long customer_id = c.getCustomer_id();
		RechargeWater rw = new RechargeWater();
		TransIdBackVo backVo = null;
		GoldCoinChangeForm gform = new GoldCoinChangeForm();
		String order_id = UUID.randomUUID().toString();
		gform.putExtrans_id(order_id).putAction_in(ActionIn.RECHARGE).putOccur_amount(new BigDecimal(10000))
				.putCif_id(ValueUtil.getLong(c.getCif_id()));
		backVo = uf30Service.goldcoinChange(gform);
		if (VOUtil.isSuccess(backVo)) {
			rw.setCharge_status(RechargeStatus.SUC.getVal());
			rw.setCharge_status_mean("手动充值成功");
		} else {
			rw.setCharge_status(RechargeStatus.ERR.getVal());
			rw.setCharge_status_mean("UF30加金币失败");
		}

		String uf30transId = ValueUtil.getString(backVo.getTrans_id());
		rw.setUf30_trans_no(uf30transId);
		rw.setTrans_id(order_id);
		rw.setPosition_str(PositionStrUtil.getPositionStr());
		rw.setCustomer_id(customer_id);
		rw.setRecharge_amount(10000);
		rw.setCharge_type(2);
		rw.setCharge_channel_mean("手动加金币");
		rw.setCreate_time(new Date());
		rechargeWaterService.save(rw);
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public HSBCPSBackVO funcFansActivityRecharge(FansFundForm form) {
		if (StringUtil.isBlank(form.getOpenid()) && StringUtil.isBlank(form.getMobile_tel())) {
			return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
		}
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, HSBCPSBackVO.class);
		}
		Customer customer;
		if (!StringUtil.isBlank(form.getMobile_tel())) {
			customer = customerService.getByMobileAndTenant(form.getMobile_tel(), tenant.getTenant_id());
		} else {
			customer = customerService.getByOpenidAndTenant(form.getOpenid(), tenant.getTenant_id());
		}
		if (customer == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
		}
		Map<String, Object> jsonObject = JSONObject.parseObject(JSONObject.toJSONString(form));
		String md5Key = ConfigValues.getMd5Key(tenant.getTenant_id());
		boolean validate = ActivityUtil.validateHashedQueryString(jsonObject, md5Key);
		if (!validate) {
			return VOUtil.genErrorResult(ClientErr.VALIDATE_FAIL, HSBCPSBackVO.class);
		}

		RechargeWater rw = new RechargeWater();
		TransIdBackVo backVo = null;
		GoldCoinChangeForm gform = new GoldCoinChangeForm();
		String order_id = UUID.randomUUID().toString();
		gform.putExtrans_id(order_id).putAction_in(ActionIn.RECHARGE).putOccur_amount(new BigDecimal(form.getAmount()))
				.putCif_id(ValueUtil.getLong(customer.getCif_id()));
		backVo = uf30Service.goldcoinChange(gform);
		if (VOUtil.isSuccess(backVo)) {
			rw.setCharge_status(RechargeStatus.SUC.getVal());
			rw.setCharge_status_mean("手动充值成功");
		} else {
			rw.setCharge_status(RechargeStatus.ERR.getVal());
			rw.setCharge_status_mean("UF30加金币失败");
		}
		String uf30transId = ValueUtil.getString(backVo.getTrans_id());
		rw.setUf30_trans_no(uf30transId);
		rw.setTrans_id(order_id);
		rw.setPosition_str(PositionStrUtil.getPositionStr());
		rw.setCustomer_id(customer.getCustomer_id());
		rw.setRecharge_amount(ValueUtil.getInt(form.getAmount()));
		rw.setCharge_type(2);
		rw.setCharge_channel_mean("手动加金币");
		rw.setCreate_time(new Date());
		rechargeWaterService.save(rw);
		return VOUtil.genSuccessResultVo();
	}

	@Override
	public BrokerListResult funcBrokerListByTenant(BrokerListTenant form) {
		BrokerListResult result = new BrokerListResult();
		if (HSBCPSBizDataContext.getCustomerNoException() == null) {
			List<BrokerListView> list = brokerService.listByTenant(form.getPosition_str(),
					Integer.parseInt(form.getRequest_num()));
			result.newDataList().addAll(list);
			updateBrokerList(list, new ArrayList<Long>());
			return VOUtil.setSuccessResult(result);
		}
		Long customer_id = HSBCPSBizDataContext.getCustomer().getCustomer_id();
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		if (brokerId != null) {
			fansBackList(HSBCPSBizDataContext.getAccess_token(), customer_id, brokerId);
		}
		Integer follow_type = Integer.valueOf(form.getFollow_type());

		if (FollowType.ALL.equals(EnumUtil.valOf(follow_type, FollowType.class))) {
			List<Long> followbrokers = customerBrokerFollowService.getBrokersByCustomerId(customer_id);
			List<BrokerListView> list = brokerService.listByTenant(form.getPosition_str(),
					Integer.parseInt(form.getRequest_num()));
			if (list != null && !list.isEmpty()) {
				updateBrokerList(list, followbrokers);
				List<BrokerListView> followList = new ArrayList<BrokerListView>();
				List<BrokerListView> imfollowList = new ArrayList<BrokerListView>();
				for (BrokerListView view : list) {
					Integer type = view.getFollow_type();
					if (1 == type) {
						followList.add(view);
					} else {
						imfollowList.add(view);
					}
				}
				followList.addAll(imfollowList);
				result.newDataList().addAll(followList);
			}
			return VOUtil.setSuccessResult(result);
		} else if (FollowType.FOLLOW.equals(EnumUtil.valOf(follow_type, FollowType.class))) {
			List<Long> followbrokers = customerBrokerFollowService.getBrokersByCustomerId(customer_id);
			List<BrokerListView> list = null;
			if (followbrokers.size() != 0) {
				list = brokerService.listByTenantFollow(form.getPosition_str(), Integer.parseInt(form.getRequest_num()),
						followbrokers);
			}
			if (list != null && !list.isEmpty()) {
				updateBrokerList(list, followbrokers);
				result.newDataList().addAll(list);
			}
			return VOUtil.setSuccessResult(result);
		} else {
			List<Long> followbrokers = customerBrokerFollowService.getBrokersByCustomerId(customer_id);
			List<BrokerListView> list = null;
			if (followbrokers.size() != 0) {
				list = brokerService.listByTenantNoFollow(form.getPosition_str(),
						Integer.parseInt(form.getRequest_num()), followbrokers);
			} else {
				list = brokerService.listByTenant(form.getPosition_str(), Integer.parseInt(form.getRequest_num()));
			}
			if (list != null && !list.isEmpty()) {
				updateBrokerList(list, followbrokers);
				result.newDataList().addAll(list);
			}
			return VOUtil.setSuccessResult(result);
		}
	}

	@Override
	public AccessTokenForm funcGetLightAccessToken(OpenIDForm form) {
		AccessTokenForm result = new AccessTokenForm();
		String token = AppAccessTokenUtil.getAppAccessToken(form.getOpen_id());
		if (token == null) {
			return VOUtil.genErrorResult(HSBCPSErrorCodes.LightErr.LIGHT_ACCESS_TOKOEN_ERR, AccessTokenForm.class);
		}
		result.setLight_access_token(token);
		return VOUtil.setSuccessResult(result);
	}

	private void updateBrokerList(List<BrokerListView> list, List<Long> followbrokers) {
		List<Long> brokers = new ArrayList<Long>();
		for (BrokerListView brokerListView : list) {
			ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerListView.getBroker_id());
			if (chatRoom != null && chatRoom.getInvitation_code() != null && !chatRoom.getInvitation_code().isEmpty()) {
				brokerListView.setInvitation_flag(0);
			} else {
				brokerListView.setInvitation_flag(1);
			}
			brokers.add(brokerListView.getBroker_id());
		}
		List<AnswerBrokerView> answerBrokerViews = answerService.queryByBrokerId(brokers);
		List<ViewpointMsgBrokerView> viewpointMsgBrokerViews = viewpointMsgService.queryByBrokerId(brokers);

		for (BrokerListView brokerListView : list) {
			for (int i = 0; i < answerBrokerViews.size(); i++) {
				if (answerBrokerViews.get(i).getBroker_id().equals(brokerListView.getBroker_id())) {
					brokerListView.setAnswer_num(answerBrokerViews.get(i).getAnswer_num());
					brokerListView.setAnswer_time(answerBrokerViews.get(i).getCreate_time());
					break;
				}
			}
			for (int i = 0; i < viewpointMsgBrokerViews.size(); i++) {
				if (viewpointMsgBrokerViews.get(i).getBroker_id().equals(brokerListView.getBroker_id())) {
					brokerListView.setViewpoint_num(viewpointMsgBrokerViews.get(i).getViewpoint_num());
					break;
				}
			}
			if (followbrokers.contains(brokerListView.getBroker_id())) {
				brokerListView.setFollow_type(1);
			} else {
				brokerListView.setFollow_type(2);
			}
		}

	}

	@Override
	public GuestResultData funcGuestToken(GuestTokenForm form) {
		GuestResultData result = new GuestResultData();
		String user_token = "";
		String access_token = "";

		Broker broker = brokerService.getByKey(form.getBroker_key());
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, GuestResultData.class);
		}

		Long customer_id = SessionHelper.getInstance().getGuestTokenFromKeys(broker.getBroker_id());
		PlatformType type = PlatformType.MOBILE;
		String clientIdToken = SessionHelper.getInstance().getSessionTokenByClientId(type, customer_id.toString());
		String userToken = CacheHelper.getInstance().get(clientIdToken);
		// 客户已经存在token，删除token
		if (!StringUtil.isEmpty(clientIdToken) && !StringUtil.isEmpty(userToken)) {
			user_token = customer_id.toString();
		} else {
			CustomerCache identity = new CustomerCache();
			identity.setClient_id(null);
			// 大V或者粉丝
			identity.setTenantId(broker.getTenant_id());
			identity.setUserType(SysContants.SESSION_USER_TYPE_FANS);
			identity.setCustomer(null);
			identity.setPlatformType(type.getValue());
			identity.setBrokerId(broker.getBroker_id());

			user_token = SessionHelper.getInstance().renewGuestUserToken(identity, customer_id.toString());

			// 把生成的token保存到缓存
			SessionHelper.getInstance().saveNewClientIDSessionWithTime(type, customer_id, user_token, null, null, -1);
		}
		access_token = AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal());

		result.setUser_token(user_token);
		result.setAccess_token(access_token);
		return VOUtil.setSuccessResult(result);
	}

	public FansAppRegLoginBackData funcFansAppRegLogin(FansAppRegLoginForm param) {
		FansAppRegLoginBackData result = new FansAppRegLoginBackData();
		/**
		 * 1.检测redis中是否存在auth_id 存在直接返回token 2.请求用户中心获取手机号 3.检查数据库是否已经注册
		 * 4.执行注册登录 或 写入登录信息
		 */

		Broker broker = brokerService.getByKey(param.getBroker_key());
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, FansAppRegLoginBackData.class);
		}
		Integer tenant_id = broker.getTenant_id();
		HSBCPSBizDataContext.setTenantId(tenant_id);
		String mobile = getMobileFromHs(param.getAuth_id());
		Customer customer = customerService.getByMobile(mobile);
		if (customer == null) {
			customer = customerService.getByKey(SysContants.AUTH_ID_PREFIX + param.getAuth_id());
			if (null == customer) {
				// 用auth_id注册用户
				customer = new Customer();
				customer.setMobile(mobile);
				customer.setAvatar(param.getCustomer_avatar());
				customer.setCustomer_name(param.getCustomer_name());
				customer = createNewCustomerByAuthId(param.getAuth_id(), tenant_id, customer, ChannelCode.ITN);
				customerBrokerRelService.saveNewRel(tenant_id, broker.getBroker_id(), customer.getCustomer_id(), "");
			}
		}

		updateCusNameAvator(customer.getCustomer_id(), tenant_id, customer.getAvatar(), customer.getCustomer_name(),
				param);
		customer.setAvatar(param.getCustomer_avatar());
		customer.setCustomer_name(param.getCustomer_name());

		CustomerBrokerRel relTemp = customerBrokerRelService.getByBrokerIdAndCustomerId(broker.getBroker_id(),
				customer.getCustomer_id());
		if (relTemp == null) {
			customerBrokerRelService.saveNewRel(tenant_id, broker.getBroker_id(), customer.getCustomer_id(), "");
		} else {
			if (BlockType.YES.getVal() == ValueUtil.getInt(relTemp.getBlock_flag(), 1)) {
				return VOUtil.genErrorResult(ClientErr.FANS_IS_BLOCK, FansAppRegLoginBackData.class);
			}
		}

		// 如果云信账号为空，注册云信
		if (StringUtil.isEmpty(customer.getYunxin_accid())) {
			customerService.yunxinReg(customer, true);
		}

		SessionIdentity sessionIdentity = customerService.createNewFansIdentity(customer, broker.getBroker_id());
		String user_token = UUID.randomUUID().toString();
		SessionHelper.getInstance().renewGuestUserToken(sessionIdentity, user_token);
		result.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
		result.setUser_token(user_token);
		result.setChannel_code(StringUtil.isEmpty(customer.getReg_source()) ? "1002" : customer.getReg_source());

		return VOUtil.setSuccessResult(result);
	}

	public Customer createNewCustomerByAuthId(String auth_id, Integer tenant_id, Customer customerOld,
			String reg_source) {
		Customer c = customerOld;
		c.setCustomer_key(SysContants.AUTH_ID_PREFIX + auth_id);
		c.setTenant_id(tenant_id);
		c.setCreate_time(new Date());
		c.setStatus(CustomerStatus.NOMAL.getVal());
		c.setFund_flag("1");
		c.setGag_flag("1");
		c.setBlock_flag("1");
		c.setReg_source(reg_source);
		customerService.save(c);
		customerService.yunxinReg(c, true);
		return c;
	}

	public boolean updateCusNameAvator(Long customer_id, Integer tenant_id, String avatar, String name,
			FansAppRegLoginForm param) {
		boolean flag = false;
		if (customer_id == null || tenant_id == null) {
			logger.info("三方注册接口 更新用户信息有误 id或tenant为空");
			flag = false;
		}

		Customer update = new Customer();
		update.setTenant_id(tenant_id);
		update.setCustomer_id(customer_id);
		if (!param.getCustomer_avatar().equals(avatar)) {
			update.setAvatar(param.getCustomer_avatar());
			flag = true;
		}
		if (!param.getCustomer_name().equals(name) && !checkUserName(param.getCustomer_name())) {
			update.setCustomer_name(param.getCustomer_name());
			flag = true;
		}
		if (flag) {
			customerService.update(update);
		}
		return flag;
	}

	public String getMobileFromHs(String auth_id) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("auth_id", auth_id);
		Map<String, Object> resultMap = itnServiceT2.getItnUserInfo(param);
		if (!VOUtil.isSuccess(resultMap)) {
			return "";
		}
		ItnUserInfoBackData userInfo = JresUtil.bodyProtocolToBean(resultMap, ItnUserInfoBackData.class);
		return userInfo.getMobile_tel();
	}

	@Override
	public HSBCPSBackVO funcFansPointRecharge(FansPointForm form) {
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResultVo(ClientErr.TENANT_NOT_EXIST);
		}
		Customer customer = customerService.getByMobileAndTenant(form.getMobile_tel(), tenant.getTenant_id());
		if (customer == null) {
			return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
		}
		Map<String, Object> jsonObject = JSONObject.parseObject(JSONObject.toJSONString(form));
		String md5Key = ConfigValues.getMd5Key(tenant.getTenant_id());
		boolean validate = ActivityUtil.validateHashedQueryString(jsonObject, md5Key);
		if (!validate) {
			return VOUtil.genErrorResultVo(ClientErr.VALIDATE_FAIL);
		}

		LTBPointChangeBackVo backVo = null;
		LTBPointAddForm ltbform = new LTBPointAddForm();
		ltbform.setUser_id(customer.getUser_id());
		ltbform.setMobile(customer.getMobile());
		ltbform.setOpera_credits(ValueUtil.getInt(form.getAmount()));
		ltbform.setCompany_id(tenant.getCompany_id());
		backVo = ltbService.funcAddPoint(ltbform);
		if (backVo != null && backVo.getError_no().equals("0")) {
			PointWater pointWater = new PointWater();
			pointWater.setCustomer_id(customer.getCustomer_id());
			pointWater.setUser_id(customer.getUser_id());
			pointWater.setPoint_amount(new BigDecimal(form.getAmount()));
			pointWater.setPoint_base_amount(
					new BigDecimal(backVo.getUser_credits()).subtract(new BigDecimal(form.getAmount())));
			pointWater.setPoint_current_amount(new BigDecimal(backVo.getUser_credits()));
			pointWater.setTrans_id(UUID.randomUUID().toString());
			pointWater.setCreate_time(new Date());
			pointWater.setCharge_type(1);
			pointWater.setPosition_str(PositionStrUtil.getPositionStr());
			pointWater.setRemark("新增积分" + form.getAmount());
			pointWater.setTenant_id(customer.getTenant_id());
			pointWaterService.save(pointWater);
			return VOUtil.genSuccessResultVo();
		} else {
			return VOUtil.genErrorResultVo(HSBCPSErrorCodes.PointErr.LTB_ERROR_NO);
		}
	}

	@Override
	public HSBCPSBackVO funcFansPointConsume(FansPointForm form) {
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResultVo(ClientErr.TENANT_NOT_EXIST);
		}
		Customer customer = customerService.getByMobileAndTenant(form.getMobile_tel(), tenant.getTenant_id());
		if (customer == null) {
			return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
		}
		Map<String, Object> jsonObject = JSONObject.parseObject(JSONObject.toJSONString(form));
		String md5Key = ConfigValues.getMd5Key(tenant.getTenant_id());
		boolean validate = ActivityUtil.validateHashedQueryString(jsonObject, md5Key);
		if (!validate) {
			return VOUtil.genErrorResultVo(ClientErr.VALIDATE_FAIL);
		}

		LTBPointChangeBackVo backVo = null;
		LTBPointAddForm ltbform = new LTBPointAddForm();
		ltbform.setUser_id(customer.getUser_id());
		ltbform.setMobile(customer.getMobile());
		ltbform.setOpera_credits(ValueUtil.getInt(form.getAmount()));
		ltbform.setCompany_id(tenant.getCompany_id());
		backVo = ltbService.funcCostPoint(ltbform);
		if (backVo != null && backVo.getError_no().equals("0")) {
			PointWater pointWater = new PointWater();
			pointWater.setCustomer_id(customer.getCustomer_id());
			pointWater.setUser_id(customer.getUser_id());
			pointWater.setPoint_amount(new BigDecimal(form.getAmount()));
			pointWater.setPoint_base_amount(
					new BigDecimal(backVo.getUser_credits()).add(new BigDecimal(form.getAmount())));
			pointWater.setPoint_current_amount(new BigDecimal(backVo.getUser_credits()));
			pointWater.setTrans_id(UUID.randomUUID().toString());
			pointWater.setCreate_time(new Date());
			pointWater.setCharge_type(0);
			pointWater.setPosition_str(PositionStrUtil.getPositionStr());
			pointWater.setRemark("消费积分" + form.getAmount());
			pointWater.setTenant_id(customer.getTenant_id());
			pointWaterService.save(pointWater);
			return VOUtil.genSuccessResultVo();
		} else if (backVo != null && backVo.getError_no().equals("206401")) {
			return VOUtil.genErrorResultVo(HSBCPSErrorCodes.PointErr.NO_BALANCE_POINT);
		} else {
			return VOUtil.genErrorResultVo(HSBCPSErrorCodes.PointErr.LTB_ERROR_NO);
		}
	}

	@Override
	public FansPointBackList funcFansPointQueryList(FansQueryForm form) {
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, FansPointBackList.class);
		}
		Customer customer = customerService.getByMobileAndTenant(form.getMobile_tel(), tenant.getTenant_id());
		if (customer == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, FansPointBackList.class);
		}
		Map<String, Object> jsonObject = JSONObject.parseObject(JSONObject.toJSONString(form));
		String md5Key = ConfigValues.getMd5Key(tenant.getTenant_id());
		boolean validate = ActivityUtil.validateHashedQueryString(jsonObject, md5Key);
		if (!validate) {
			return VOUtil.genErrorResult(ClientErr.VALIDATE_FAIL, FansPointBackList.class);
		}

		Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
		Integer pageSize = ValueUtil.getInt(form.getPage_count(), 10);
		Integer counts = pointWaterService.countByCustomer(customer.getCustomer_id(), tenant.getTenant_id());
		List<PointWater> pointWaters = pointWaterService.getByCustomer(customer.getCustomer_id(), tenant.getTenant_id(),
				(pageNo - 1) * pageSize, pageSize);

		FansPointBackList fansPointBackList = new FansPointBackList();
		if (pointWaters != null && !pointWaters.isEmpty()) {
			List<FansPointDetailBackForm> dataList = new ArrayList<FansPointDetailBackForm>();

			for (PointWater pointWater : pointWaters) {

				FansPointDetailBackForm fansPointDetailBackForm = new FansPointDetailBackForm();
				fansPointDetailBackForm.setSerial_no(pointWater.getPoint_water_id().toString());
				fansPointDetailBackForm
						.setInit_date(DateUtil.dateToStr(pointWater.getCreate_time(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				fansPointDetailBackForm.setCurr_date(DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD));
				fansPointDetailBackForm.setCurr_time(DateUtil.dateToStr(new Date(), DateUtil.HH_MM_SS));
				fansPointDetailBackForm.setExtrans_id(pointWater.getTrans_id());
				fansPointDetailBackForm.setOccur_amount(pointWater.getPoint_amount());
				fansPointDetailBackForm.setBase_amount(pointWater.getPoint_base_amount());
				fansPointDetailBackForm.setCurrent_amount(pointWater.getPoint_current_amount());
				fansPointDetailBackForm.setCharge_type(pointWater.getCharge_type());
				fansPointDetailBackForm.setPosition_str(pointWater.getPosition_str());
				fansPointDetailBackForm.setRemark(pointWater.getRemark());
				dataList.add(fansPointDetailBackForm);
			}

			fansPointBackList.newDataList().addAll(dataList);

		}
		fansPointBackList.setTotal_item_num(counts);
		fansPointBackList.setPage_no(ValueUtil.getInt(form.getPage_no(), 1));
		return VOUtil.setSuccessResult(fansPointBackList);

	}

	@Override
	public FansPointBackForm funcFansPointQuery(FansBalanceForm form) {
		Tenant tenant = tenantService.getByKey(form.getTenant_key());
		if (tenant == null) {
			return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, FansPointBackForm.class);
		}
		Customer customer = customerService.getByMobileAndTenant(form.getMobile_tel(), tenant.getTenant_id());
		if (customer == null) {
			return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, FansPointBackForm.class);
		}
		Map<String, Object> jsonObject = JSONObject.parseObject(JSONObject.toJSONString(form));
		String md5Key = ConfigValues.getMd5Key(tenant.getTenant_id());
		boolean validate = ActivityUtil.validateHashedQueryString(jsonObject, md5Key);
		if (!validate) {
			return VOUtil.genErrorResult(ClientErr.VALIDATE_FAIL, FansPointBackForm.class);
		}

		LTBPointQueryBackVo backVo = null;
		LTBPointQryForm ltbform = new LTBPointQryForm();
		ltbform.setUser_id(customer.getUser_id());
		ltbform.setMobile(customer.getMobile());
		ltbform.setCompany_id(tenant.getCompany_id());
		backVo = ltbService.funcGetPointQry(ltbform);
		if (backVo != null && backVo.getError_no().equals("0")) {
			FansPointBackForm fansPointBackForm = new FansPointBackForm();
			fansPointBackForm.setCurrent_amount(new BigDecimal(backVo.getUser_credits()));
			fansPointBackForm.setTotal_amount(new BigDecimal(backVo.getHistory_credits()));
			return VOUtil.setSuccessResult(fansPointBackForm);
		} else {
			return VOUtil.genErrorResult(HSBCPSErrorCodes.PointErr.LTB_ERROR_NO, FansPointBackForm.class);
		}

	}

	@Override
	public FansPointBackForm funcFansPointQueryLogin(HSBCPSVO form) {
		Integer tenantId = HSBCPSBizDataContext.getTenantId();
		Integer companyId = tenantService.getCompanyIdByTenantId(tenantId);
		Customer customer = HSBCPSBizDataContext.getCustomer();
		LTBPointQryForm ltbPointQryForm = new LTBPointQryForm();
		ltbPointQryForm.setCompany_id(ValueUtil.getString(companyId));
		ltbPointQryForm.setMobile(customer.getMobile());
		ltbPointQryForm.setUser_id(customer.getUser_id());
		LTBPointQueryBackVo ltbPointQueryBackVo = ltbService.funcGetPointQry(ltbPointQryForm);
		if (ltbPointQueryBackVo != null && ltbPointQueryBackVo.getError_no().equals("0")) {
			FansPointBackForm fansPointBackForm = new FansPointBackForm();
			fansPointBackForm.setCurrent_amount(new BigDecimal(ltbPointQueryBackVo.getUser_credits()));
			fansPointBackForm.setTotal_amount(new BigDecimal(ltbPointQueryBackVo.getHistory_credits()));
			return VOUtil.setSuccessResult(fansPointBackForm);
		} else {
			return VOUtil.genErrorResult(HSBCPSErrorCodes.PointErr.LTB_ERROR_NO, FansPointBackForm.class);
		}
	}

	@Override
	public BrokerDropdownList funcBrokerDropdownListByTenant(ListQueryVO form) {
		BrokerDropdownList result = new BrokerDropdownList();
		Long customer_id = HSBCPSBizDataContext.getCustomer().getCustomer_id();

		List<Long> followbrokers = customerBrokerFollowService.getBrokersByCustomerId(customer_id);
		List<BrokerDropdownListView> list = null;
		if (followbrokers.size() != 0) {
			list = brokerService.dropdownListByTenant(form.getPosition_str(), Integer.parseInt(form.getRequest_num()),
					followbrokers);
		}
		if (list != null && !list.isEmpty()) {
			result.newDataList().addAll(list);
		}
		return VOUtil.setSuccessResult(result);
	}

	@Override
	public HSBCPSBackVO funcActionLog(ActionLogForm form) {
		Long actionPage = ValueUtil.getLong(form.getAction_page());
		Long actionType = ValueUtil.getLong(form.getAction_type());
		String actionName = form.getAction_name();
		String url = form.getUrl();
		String remark = form.getRemark();
		Action action = new Action();
		Integer tenantId = HSBCPSBizDataContext.getTenantId();
		Customer customer = HSBCPSBizDataContext.getCustomerNoException();
		if (customer == null) {
			return VOUtil.genSuccessBackVo();
		}
		Long brokerId = HSBCPSBizDataContext.getBrokerId();
		action.setAction_page(actionPage);
		action.setAction_type(actionType);
		action.setAction_name(actionName);
		action.setUrl(url);
		action.setRemark(remark);
		action.setTenant_id(tenantId);
		action.setCustomer_id(customer.getCustomer_id());
		action.setBroker_id(brokerId);
		action.setCreate_time(new Date());
		actionService.save(action);
		return VOUtil.genSuccessBackVo();
	}

	@Override
	public FansPointUrlBackForm funcFansPointUrl(HSBCPSVO form) {
		Integer tenantId = HSBCPSBizDataContext.getTenantId();
		Customer customer = HSBCPSBizDataContext.getCustomer();
		String pointGetUrl = ConfigValues.getPointUrl(tenantId);
		String pointAppKey = ConfigValues.getPointAppKey(tenantId);
		String pointAppSecret = ConfigValues.getPointAppSecret(tenantId);
		Map<String, String> signMap = new TreeMap<String, String>();
		Map<String, Object> urlMap = new TreeMap<String, Object>();
		signMap.put("open_id", ValueUtil.getString(customer.getCustomer_id()));
		signMap.put("app_secret", pointAppSecret);
		signMap.put("app_key", pointAppKey);
		signMap.put("timestamp", ValueUtil.getString(new Date().getTime()));
		if (!StringUtil.isBlank(customer.getCustomer_name())) {
			signMap.put("nick_name", customer.getCustomer_name());
		}
		if (!StringUtil.isBlank(customer.getMobile())) {
			signMap.put("mobile_tel", customer.getMobile());
		}
		if (!StringUtil.isBlank(customer.getProvince_name())) {
			signMap.put("province", customer.getProvince_name());
		}
		if (!StringUtil.isBlank(customer.getCity_name())) {
			signMap.put("city", customer.getCity_name());
		}
		if (!StringUtil.isBlank(customer.getQq_open_id())) {
			signMap.put("qq", customer.getQq_open_id());
		}
		String sign = SignUtils.sign(signMap);

		urlMap.put("open_id", ValueUtil.getString(customer.getCustomer_id()));
		urlMap.put("sign", sign);
		urlMap.put("app_key", pointAppKey);
		urlMap.put("timestamp", ValueUtil.getLong(signMap.get("timestamp")));
		if (!StringUtil.isBlank(customer.getCustomer_name())) {
			urlMap.put("nick_name", customer.getCustomer_name());
		}
		if (!StringUtil.isBlank(customer.getMobile())) {
			urlMap.put("mobile_tel", customer.getMobile());
		}
		if (!StringUtil.isBlank(customer.getProvince_name())) {
			urlMap.put("province", customer.getProvince_name());
		}
		if (!StringUtil.isBlank(customer.getCity_name())) {
			urlMap.put("city", customer.getCity_name());
		}
		if (!StringUtil.isBlank(customer.getQq_open_id())) {
			urlMap.put("qq", customer.getQq_open_id());
		}

		String pointResponseS = HttpsUtil.doHttpsPost(pointGetUrl, urlMap);
		FansPointUrlBackForm fansPointUrlBackForm = new FansPointUrlBackForm();
		if (StringUtil.isBlank(pointResponseS) || JSON.parseObject(pointResponseS).getJSONObject("data") == null){
			return VOUtil.setSuccessResult(fansPointUrlBackForm);
		}
		String pointUrl = JSON.parseObject(pointResponseS).getJSONObject("data").getString("location");
		fansPointUrlBackForm.setPoint_url(pointUrl);
		return VOUtil.setSuccessResult(fansPointUrlBackForm);
	}

	@Override
	public BrokerInfoByUserIdBack funcGetBrokerInfoByUserId(BrokerInfoByUserIdForm form) {
		BrokerManager brokerManager = brokerManagerService.getByUserId(ValueUtil.getLongObj(form.getUser_id()));
		if (brokerManager == null) {
			return VOUtil.genErrorResult(ClientErr.BROKER_NOT_FIND, BrokerInfoByUserIdBack.class);
		}
		Broker broker = brokerService.get(String.valueOf(brokerManager.getBroker_id()));
		if (broker == null) {
			return VOUtil.genErrorResult(ClientErr.BROKER_NOT_FIND, BrokerInfoByUserIdBack.class);
		}
		BrokerInfoByUserIdBack back = new BrokerInfoByUserIdBack();
		back.setBroker_key(broker.getBroker_key());
		back.setBroker_id(broker.getBroker_id());
		return VOUtil.setSuccessResult(back);
	}

	@Override
	public SurveyStatusList funcSurveyStatusList(SurveyStatusListForm form) {
		SurveyStatusList statusList = new SurveyStatusList();
		statusList.newDataList();
		Long customerId = HSBCPSBizDataContext.getCustomer().getCustomer_id();
		String[] surveyIds = form.getSurvey_ids().split(",");
		List<Long> targetIds = new ArrayList<>();
		for (int index = 0; index < surveyIds.length; index++) {
			targetIds.add(ValueUtil.getLong(surveyIds[index]));
		}
		List<Long> list = payWaterService.queryPayViewIds(customerId, targetIds, PaySource.SURVEY);
		for (Long targetId : targetIds) {
			SurveyStatusData data = new SurveyStatusData();
			if (list.contains(targetId)) {
				// 支付为1
				data.setSurvery_status("1");
			} else {
				// 未支付为0
				data.setSurvery_status("0");
			}
			data.setSurvery_id(targetId);
			statusList.getData_list().add(data);
		}
		return VOUtil.setSuccessResult(statusList);
	}

}
